/**
 * File:bc
 * Youth is just a unoptimized code!
 * -------------------------------------------------------------------------
 * Created by BigQ on 2016/9/22.
 *--------------------------------------------------------------------------
 * This technical information is confidential information,
 * without my written permission is prohibited for commercial purposes.　
 *--------------------------------------------------------------------------
 */
/**
 * bc扩展
 */
(function ($) {
    //全局系统对象
    window['BC'] = {};
    //显示提示窗口
    BC.alert = function (message, callback) {
        message = message || "提示信息";
        $.jBox.alert(message, '提示信息', {
            closed: function () {
                if (callback && typeof (callback) == "function") {
                    callback();
                }
            }
        });
    };
    //确认对话框
    BC.confirm = function (message, ok, cancel) {
        message = message || "您确定？";
        $.jBox.confirm(message, "确认提醒", function (v, h, f) {
            if (v == 'ok') {
                if (ok && typeof (ok) == "function") {
                    ok();
                }
            }
            else if (v == 'cancel') {
                if (cancel && typeof (cancel) == "function") {
                    cancel();
                }
            }
            return true; //close
        });

    };
    //显示提示窗口
    BC.showInfo = function (message, callback) {
        message = message || "提示信息";
        $.jBox.info(message, '提示信息', {
            closed: function () {
                if (callback && typeof (callback) == "function") {
                    callback();
                }
            }
        });
    };
    //显示成功提示窗口
    BC.showSuccess = function (message, callback) {
        message = message || "成功！";
        $.jBox.success(message, '成功提示', {
            closed: function () {
                if (callback && typeof (callback) == "function") {
                    callback();
                }
            }
        });
    };
    //显示警告提示窗口
    BC.showWarning = function (message, yes, no, cancel) {
        message = message || "警告！";
        $.jBox.warning(message, '警告提示', function (v, h, f) {
            console.log(v);
            if (v == 'yes') {
                if (yes && typeof (yes) == "function") {
                    yes();
                }
            }
            else if (v == 'no') {
                if (no && typeof (no) == "function") {
                    no();
                }
            }
            else if (v == 'cancel') {
                if (cancel && typeof (cancel) == "function") {
                    cancel();
                }
            }
        });
    };
    //显示错误提示窗口
    BC.showError = function (message, callback) {
        message = message || "错误！";
        $.jBox.error(message, '错误提示', {
            closed: function () {
                if (callback && typeof (callback) == "function") {
                    callback();
                }
            }
        });
    };

    //显示提示信息
    BC.tip = function (message, callback) {
        message = message || "错误！";
        $.jBox.tip(message, 'info', {
            closed: function () {
                if (callback && typeof (callback) == "function") {
                    callback();
                }
            }
        });
    };
    //显示成功信息
    BC.tipSuccess = function (message, callback) {
        message = message || "成功！";
        $.jBox.tip(message, 'success', {
            closed: function () {
                if (callback && typeof (callback) == "function") {
                    callback();
                }
            }
        });
    };
    //显示警告信息
    BC.tipWarning = function (message, callback) {
        message = message || "警告！";
        $.jBox.tip(message, 'warning', {
            closed: function () {
                if (callback && typeof (callback) == "function") {
                    callback();
                }
            }
        });
    };
    //显示警告信息
    BC.tipError = function (message, callback) {
        message = message || "错误！";
        $.jBox.tip(message, 'error', {
            closed: function () {
                if (callback && typeof (callback) == "function") {
                    callback();
                }
            }
        });
    };
    /**
     * 显示加载
     * @param message
     */
    BC.tipLoading = function (message) {
        message = message || "加载中...";
        $.jBox.tip(message, 'loading');
    };
    //关闭Tip
    BC.hideLoading = BC.closeTip = function () {
        //$.jBox.closeTip();
        setTimeout(function(){ $.jBox.closeTip();  },1000)
    };
    /**
     * 发送数据请求
     * @param options
     */
    BC.ajax = function (options) {
        //默认值
        var defaultOpt = {
            url: '',
            controller: '',
            action: '',
            async: true,
            showLoading: true,
            loadingTip: "数据请求中...",
            type: 'post',
            dataType: 'json',
            data: '',
            beforeSend: null,
            complete: null,
            success: null,
            fail: null,
            error: null
        };
        var p = $.extend({},defaultOpt, options || {});
        if ($.isEmptyObject(p.url)) {
            p.url = $.isEmptyObject(p.controller) ? p.action : '/' + p.controller + '/' + p.action;
        }
        $.ajax({
            cache: false,
            async: p.async,
            url: p.url,
            data: p.data,
            dataType: p.dataType,
            type: p.type,
            beforeSend: function () {
                if (p.showLoading) {
                    BC.tipLoading(p.loadingTip);
                }
                if (p.beforeSend) {
                    p.beforeSend();
                }

            },
            complete: function () {
                if (p.showLoading) {
                    BC.hideLoading();
                }
                if (p.complete) {
                    p.complete();
                }

            },
            success: function (result) {
                if (!result) return;
                if (p.dataType.toLowerCase() == 'json' || p.dataType.toLowerCase() == 'jsonp') {
                    if (result.status == 1) {
                        if (p.success) {
                            p.success(result.message,result.data);
                        }
                    }
                    else {
                        if (p.fail) {
                            p.fail(result.message,result.data);
                        }
                    }
                }
                else {
                    if (p.success) {
                        p.success(result);
                    }
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                if (p.error) {
                    p.error(XMLHttpRequest, textStatus, errorThrown);
                }
                else {
                    BC.showError("系统发生错误！["+textStatus+"]");
                }
            }
        });
    };
    /**
     * ajax提交表单
     * @param data
     * @param success
     * @param fail
     * @param complete
     */
    BC.submitForm = function (success, fail, complete) {
        //默认值
        var curUrl = window.location.href;
        var defaultOpt = {
            url: curUrl.split('?')[0],
            loadingTip: "数据提交中...",
            data: $('form').serialize(),
            complete: null,
            success: function(message,data){
                BC.showSuccess(message,function () {
                   BC.redirect(curUrl);
                });
            },
            fail:  function(message){
                BC.showError(message);
            }
        };
        if (success) {
            defaultOpt.success = success;
        }
        if (fail) {
            defaultOpt.fail = fail;
        }
        if (complete) {
            defaultOpt.complete = complete;
        }
        //文件
        var fileElemts =$(':file', $('form'));
        var fileElemArr = [];
        if(fileElemts){
            fileElemts.each(function () {
                if($(this).val() != "") {
                    fileElemArr.push($(this).attr('id'));
                }
            });
        }
        if(fileElemArr.length > 0){
           $.extend(defaultOpt,{fileInputId:fileElemArr});
            BC.fileUpload(defaultOpt);
        }
        else{
        //发送数据请求
           BC.ajax(defaultOpt);
        }
    };
    //文件上传
    BC.fileUpload = function (options) {
        //默认值
        var defaultOpt = {
            url: '',
            fileInputId: 'file',
            showLoading: true,
            loadingTip: "正在上传中...",
            dataType: 'json',
            data:{},
            complete: null,
            success: null,
            fail:null,
            error: null
        };
        $.extend(defaultOpt, options);
        $(document).ajaxStart(function () {
            //开始上传
            if (defaultOpt.showLoading) {
                BC.tipLoading(defaultOpt.loadingTip);
            }
        }).ajaxComplete(function () {
            // 文件上传完成
            if (defaultOpt.showLoading) {
                BC.hideLoading();
            }
            if (defaultOpt.complete) {
                defaultOpt.complete();
            }
        });
        if (typeof(defaultOpt.data) === 'Object') {
            defaultOpt.data = $.param(defaultOpt.data);
        }
        $.ajaxFileUpload
        (
            {
                url: defaultOpt.url + '?_tmp=' + Math.random(), // 用于文件上传的服务器端请求地址
                secureuri: false, // 一般设置为false
                fileElementId: defaultOpt.fileInputId, // 文件上传空间的id属性
                dataType: defaultOpt.dataType, // 返回值类型 一般设置为json
                data:defaultOpt.data,
                success: function (result)  // 服务器成功响应处理函数
                {
                    if (defaultOpt.dataType.toLowerCase() == 'json' || defaultOpt.dataType.toLowerCase() == 'jsonp') {
                        if (1 == result.status) {
                            if (defaultOpt.success) {
                                defaultOpt.success(result.message,result.data);
                            }
                        }
                        else {
                            if (defaultOpt.fail) {
                                defaultOpt.fail(result.message,result.data);
                            }
                        }
                    }
                    else {
                        if (defaultOpt.success) {
                            defaultOpt.success(result);
                        }
                    }
                },
                error: function (result, b)// 服务器响应失败处理函数
                {
                    if (defaultOpt.error) {
                        defaultOpt.error(result, b);
                    }
                    else {
                        console.log(result);
                        BC.showError("系统发生错误！");

                    }
                }
            }
        );
    };
    // Ajax 文件下载
    BC.download = function (url, data, method) {
        // 获取url和data
        if (url) {
            // data 是 string 或者 array/object
            data = typeof (data) == 'string' ? data : $.param(data);
            // 把参数组装成 form的  input
            var inputs = '';
            $.each(data.split('&'), function () {
                var pair = this.split('=');
                inputs += '<input type="hidden" name="' + pair[0] + '" value="' +decodeURIComponent(pair[1].replace(/\+/g, '%20'))+ '" />';
            });
            // request发送请求
            $('<form action="' + url + '" method="' + (method || 'post') + '">' + inputs + '</form>')
                .appendTo('body').submit().remove();
        }
    };
    //构建form
    BC.createForm = function (url,data,method,target) {
        if (url) {
            // data 是 string 或者 array/object
            data = typeof (data) == 'string' ? data : $.param(data);
            target = target||"";
            if(!$.isEmptyObject(target)){
                target = ' target="'+target+'"';
            }
            // 把参数组装成 form的  input
            var inputs = '';
            $.each(data.split('&'), function () {
                var pair = this.split('=');
                inputs += '<input type="hidden" name="' + pair[0] + '" value="' +decodeURIComponent(pair[1].replace(/\+/g, '%20'))+ '" />';
            });
            // request发送请求
            $('<form action="' + url + '" method="' + (method || 'post') + '"'+target+'>' + inputs + '</form>')
                .appendTo('body').submit().remove();
        }
    };
    /**
     * 获取二级代码意义
     * @param options
     * @returns {string}
     */
    BC.getCodeText = function (options) {
        var jsonArr = options.jsonArr || [];
        var code = options.code || "";
        var value = "";
        $.each(jsonArr, function (index, item) {
            if (item.code == code) {
                value = item.text || item.name;
                return;
            }
        });
        if (value == "") {
            value = BC.getColorString("未知", "red");
        }
        return value;

    };
    //获取二级代码意义
    BC.getClassName = function (options) {
        var jsonArr = options.jsonArr || [];
        var id = options.id || "";
        var value = "";
        $.each(jsonArr, function (index, item) {
            if (item.id == id) {
                value =item.name;
                return;
            }
        });
        if (value == "") {
            value = BC.getColorString("未知", "red");
        }
        return value;

    };
    //刷新当前页面
    BC.reloadPage = function () {
        window.location.reload();
    };
    //跳转页面
    BC.redirect = function (url) {
        window.location.href = url;
    };
    //日期格式化
    BC.formatDate=function (value, format) {
        function getFormat(date, dateformat) {
            if (isNaN(date)) return '';
            var formatOpt = dateformat||'yyyy-MM-dd hh:mm:ss';
            var o = {
                "M+": date.getMonth() + 1,
                "d+": date.getDate(),
                "h+": date.getHours(),
                "m+": date.getMinutes(),
                "s+": date.getSeconds(),
                "q+": Math.floor((date.getMonth() + 3) / 3),
                "S+": date.getMilliseconds()
            }
            if (/(y+)/.test(formatOpt)) {
                formatOpt = formatOpt.replace(RegExp.$1, (date.getFullYear() + "")
                    .substr(4 - RegExp.$1.length));
            }
            for (var k in o) {
                if (new RegExp("(" + k + ")").test(formatOpt)) {
                    formatOpt = formatOpt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k]
                        : ("00" + o[k]).substr(("" + o[k]).length));
                }
            }
            return formatOpt;
        }

        if (!value) return "";
        // /Date(1328423451489)/
        if (typeof (value) == "string" && /^\/Date/.test(value)) {
            value = value.replace(/^\//, "new ").replace(/\/$/, "");
            eval("value = " + value);
        }
        if(!isNaN(value)){
            var newDate = new Date();
             newDate.setTime(value * 1000);
            value =newDate;
         }
        if (value instanceof Date) {
            var formatOpt =  format || "yyyy-MM-dd hh:mm:ss";
            return getFormat(value, formatOpt);
        }
        else{

            return value.toString();
        }
    };
    //拼接查询数据
    BC.buildSearchData = function (searhFormArea) {
        var arrayObj = []
        var id = searhFormArea || "#searchForm";
        var sf = $(id);
        sf.find("input, select, textarea")
            .not("[id$='_val'],[id$='_txt'],:submit, :button,:reset, :image, [disabled]").each(function () {
            arrayObj.push({"name": "" + $(this).attr("name") + "", "value": "" + $(this).val() + ""});
        });
        return arrayObj;

    };
    //通用搜索
    BC.search = function (searhFormArea, grid) {
        if (!grid) {
            return;
        }
        grid.set({params: BC.buildSearchData(searhFormArea)});
        grid.loadData(true);

    };
    //显示图表
    BC.createChart = function (container, data) {
        $(container).html("");
        $(container).highcharts(data);
    };

    ///地区联动
    BC.changeArea = function (ddcontrol, childcontrol, tchildcotrol) {
        var ddobj = $(ddcontrol);
        var childobj = $(childcontrol);
        var tchildobj = $(tchildcotrol);
        if (ddobj && childobj) {
            $.getJSON("../handler/areahandler.ashx?pid=" + ddobj.val(), function (result) {
                childobj.empty();
                childobj.append("<option value=\"\">请选择...</option>");
                $.each(result, function (i, item) {
                    childobj.append("<option value='" + item.id + "'>" + item.name + "</option>");
                });
                childobj.val("");
                var autoc = $("#ibsauto_" + childobj.attr("id"));
                if (autoc) {
                    autoc.val(childobj.find("option:selected").text());
                }
                if (tchildobj) {
                    tchildobj.empty();
                    tchildobj.append("<option value=''>请选择...</option>");
                    tchildobj.val("");
                    var autoc = $("#ibsauto_" + tchildobj.attr("id"));
                    if (autoc) {
                        autoc.val(childobj.find("option:selected").text());
                    }
                }
            });
        }

    };
    //获取颜色样式文件
    BC.getColorString = function (str, color) {
        return '<span style="color:' + color + ';">' + str + '</span>';

    };
    //获取颜色样式文字
    BC.getYesNoColorString = function (flag) {
        if (parseInt(flag) == 1) {
            return BC.getColorString("是", "green");
        } else {
            return BC.getColorString("否", "red");
        }
    };
    //获取颜色样式文字
    BC.getYesNoString = function (flag) {
        if (parseInt(flag) == 1) {
            return "是";
        } else {
            return "否";
        }
    };
    //打开URL窗口
    BC.openUrlWindow = function (url, title, closed) {
        var t = title || url;
        $.jBox.open("iframe:" + url, t, 500, 600, {
            buttons: {'关闭': true}, closed: function () {
                if (closed && typeof (closed) == "function") {
                    closed();
                }
            }
        });
    };
    //打开HTML窗口
    BC.openHtmlWindow = function (html, title, okcall, closed) {
        var t = title || '窗口';
        /* 点击窗口按钮后的回调函数，返回true时表示关闭窗口，
         参数有三个，v表示所点的按钮的返回值，h表示窗口内容的jQuery对象，f表示窗口内容里的form表单键值 */
        var submit = function (v, h, f) {
            if (okcall && typeof (okcall) == "function") {
                return okcall(v, h, f);
            } else {
                return true;
            }
        };
        $.jBox.open(html, t, 400, 'auto', {
            submit: submit, closed: function () {
                if (closed && typeof (closed) == "function") {
                    closed();
                }
            }
        });
    };
    //创建打开窗口的string
    BC.buildWindowOpenString = function (url, title) {
        var t = title || url;
        return "<a href=\"javascript:void(0);\" onclick=\"window.open('" + url + "');\">" + t + "</a>";
    };
    /****键盘事件*****/
    //回车
    BC.readyKeyEnter = function (selector, callback) {
        $(selector).bind("keydown", function (even) {
            var ev = document.all ? window.event : even;
            if (ev) {
                if (ev.keyCode == 13) {
                    if (callback) {
                        callback();
                    }
                }

            }
        });
    };
    /**
     * 验证表单
     * @param form
     * @returns {*}
     */
    BC.validateForm = function (form) {
        if (form) {
            if (form instanceof jQuery) {
                return form.valid();
            }
            else {
                return $(form).valid();
            }

        }
        else {
            return $("form").valid();
        }
    };
    /* BC.addValidateTip = function (jqObj,option) {
     var  defaultOpt ={
     message:'数据验证未通过！',
     isInlineShow:true,
     isAfterShow:true,
     };

     return tip;

     };*/
    BC.goBack = function(){
        history.back(-1);
    };
    BC.maskShow=function () {
        var maskEle = $('<div class=".maskEle" style="display:none;position: absolute;width: 100%;height: 100%;background: rgba(0,0,0,0.5);left: 0px;top: 0px;z-index: 400;"></div>');
        $('body').append(maskEle);
        maskEle.show();
    };
    BC.maskHide=function () {
        $('.maskEle').remove();
    };
    //替换所有的回车换行
    BC.renderNewLineHtml=function (content) {
        var string = content;
        try{
            string=string.replace(/\r\n/g,"<BR>")
            string=string.replace(/\n/g,"<BR>");
        }catch(e) {
           // string =
        }
        return string;
    };

	/**
     * ajax提交表单
     * @param data
     * @param dataAjaxUrl
     * @param success
     * @param fail
     * @param complete
     */
    BC.submitFormUrl = function (dataAjaxUrl,data,success, fail, complete) {
        //默认值
        var curUrl = dataAjaxUrl;
        var defaultOpt = {
            url: curUrl.split('?')[0],
            loadingTip: "数据提交中...",
            data: data,
            complete: null,
            success: function(message,data){
                BC.showSuccess(message,function () {
                    BC.redirect(curUrl);
                });
            },
            fail:  function(message){
                BC.showError(message);
            }
        };
        if (success) {
            defaultOpt.success = success;
        }
        if (fail) {
            defaultOpt.fail = fail;
        }
        if (complete) {
            defaultOpt.complete = complete;
        }
        //文件
        var fileElemts =$(':file', $('form'));
        var fileElemArr = [];
        if(fileElemts){
            fileElemts.each(function () {
                if($(this).val() != "") {
                    fileElemArr.push($(this).attr('id'));
                }
            });
        }
        if(fileElemArr.length > 0){
            $.extend(defaultOpt,{fileInputId:fileElemArr});
            BC.fileUpload(defaultOpt);
        }
        else{
            //发送数据请求
            BC.ajax(defaultOpt);
        }
    };



})(jQuery);